package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.mapper.RoleDirWMapper;
import com.mk.model.entity.RoleDirW;
import com.mk.service.IRoleDirWService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 3:25 PM 3/21/18
 */
@Service
public class RoleDirWService extends BaseService<RoleDirWMapper,RoleDirW> implements IRoleDirWService {

    @Override
    public RoleDirW save(Long roleId, Long wDir) {
        if(roleId == null || wDir == null)
            return null;
        RoleDirW roleDirW = new RoleDirW();
        roleDirW.setRoleId(roleId);
        roleDirW.setwDir(wDir);
        return super.insert(roleDirW) ? roleDirW : null;
    }

    @Override
    public boolean deleteByDir(Long dirId) {
        return super.delete(new EntityWrapper<RoleDirW>().eq("w_dir",dirId));
    }

    @Override
    public boolean changeRoleWDir(Long roleId, List<Long> wDirs) {
        if(roleId == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入角色信息");
        super.delete(new EntityWrapper<RoleDirW>().eq("role_id",roleId));
        List<RoleDirW> roleDirWS = new ArrayList<>();
        if(!CollectionUtils.isEmpty(wDirs)){
            for (Long wDir : wDirs) {
                RoleDirW roleDirW = new RoleDirW();
                roleDirW.setRoleId(roleId);
                roleDirW.setwDir(wDir);
                roleDirWS.add(roleDirW);
            }
        }
        return super.insertBatch(roleDirWS);
    }

    @Override
    public List<Long> findByRoleId(Long roleId) {
        return baseMapper.findByRole(roleId);
    }

    @Override
    public RoleDirW findByDir(Long roleId, Long wDir) {
        return super.selectOne(new EntityWrapper<RoleDirW>().eq("role_id",roleId)
                .eq("w_dir",wDir));
    }
}
